﻿
function CreateCommentsAgregatorViewModel(containerId, pageContentGuid, pathToApiController) {

    var viewModel = {};

    var callAjax = function (ajaxParameters) {

        if (!ajaxParameters || !ajaxParameters.url)
            return;

        $.ajax({
            type: ajaxParameters.type || "GET",
            data: ajaxParameters.data || "",
            contentType: ajaxParameters.contentType || "application/json; charset=utf-8",
            url: ajaxParameters.url,
            success: ajaxParameters.success,
            error: ajaxParameters.error || function (errorObject, responseText, errorMessage) {
                if (ajaxParameters.errorMessageSetter)
                    ajaxParameters.errorMessageSetter(errorMessage);
            }
        });
    };

    viewModel.CommentBody = ko.observable();
    viewModel.Comments = ko.observableArray();
    viewModel.LoadingInProgress = ko.observable(true);
    viewModel.ErrorMessage = ko.observable();

    viewModel.GetComments = function () {

        callAjax({
            type: "GET",
            url: pathToApiController + "/GetComments",
            data: { parentContentGuid: pageContentGuid },
            success: function (data) {

                viewModel.Comments(data);
                viewModel.LoadingInProgress(false);

            },
            errorMessageSetter: function (errorMessage) {
                
                viewModel.LoadingInProgress(false);
                viewModel.ErrorMessage(errorMessage);
                
            }
        });
    };

    viewModel.AddComment = function () {

        var dataToSend = {
            parentContentGuid: pageContentGuid,
            commentBody: viewModel.CommentBody()
        };

        callAjax({
            type: 'POST',
            url: pathToApiController + "/AddComment",
            data: JSON.stringify(dataToSend),
            success: function () {
                
                viewModel.GetComments();
                viewModel.CommentBody("");
                
            },
            errorMessageSetter: viewModel.ErrorMessage
        });
    };


    $(document).ready(function () {
        ko.applyBindings(viewModel, $('#' + containerId)[0]);
        viewModel.LoadingInProgress(true);
        viewModel.GetComments();
    });

    return viewModel;
};